package com.zw.yzk.kabu.view.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.adapter.ExhibitionListAdapter;
import com.zw.yzk.kabu.base.BaseFragment;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.internal.component.DaggerExhibitionComponent;
import com.zw.yzk.kabu.internal.module.ActivityModule;
import com.zw.yzk.kabu.internal.module.ExhibitionModule;
import com.zw.yzk.kabu.model.ExhibitionModel;
import com.zw.yzk.kabu.presenter.ExhibitionPresenter;
import com.zw.yzk.kabu.view.activity.MainActivity;
import com.zw.yzk.kabu.view.activity.SearchExhibitionActivity;
import com.zw.yzk.kabu.view.activity.SelectCityActivity;
import com.zw.yzk.kabu.view.view.ExhibitionView;
import com.zw.yzk.refresh.library.PullToRefreshLayout;
import com.zw.yzk.refresh.library.RefreshBuilder;
import com.zw.yzk.refresh.library.State;
import com.zw.yzk.refresh.library.loadmore.DefaultLoadMoreViewCreator;
import com.zw.yzk.refresh.library.refrsh.DefaultRefreshViewCreator;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.OnClick;
import cn.finalteam.toolsfinal.DateUtils;

import static cn.finalteam.toolsfinal.DateUtils.getTime;

/**
 * Created by zhanwei on 2016/12/28.
 */

public class ExhibitionFragment extends BaseFragment implements ExhibitionView {

    @Bind(R.id.refresh_view)
    PullToRefreshLayout refreshLayout;
    @Bind(R.id.exhibitions)
    RecyclerView exhibitions;
    @Bind(R.id.filter_layout)
    View filterLayout;
    @Bind(R.id.month)
    TextView date;
    @Bind(R.id.city)
    TextView city;
    @Bind(R.id.no_data)
    TextView noData;

    @Inject
    ExhibitionPresenter presenter;
    private MainActivity activity;
    private ExhibitionListAdapter adapter;
    private List<String> monthList;
    private boolean getLocalData;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (MainActivity) context;
    }

    @Override
    protected int setContent() {
        return R.layout.fragment_exhibition;
    }

    @Override
    protected void initView(View view) {
        initMonthList();
        initRecyclerView();
        initFilter();
        getExhibitionList(0, null, null, true);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.destroy();
        }
    }

    @Override
    public void loadData() {
    }

    @Override
    public void initComponent() {
        DaggerExhibitionComponent.builder()
                .applicationComponent(activity.getApplicationComponent())
                .activityModule(new ActivityModule(activity))
                .exhibitionModule(new ExhibitionModule())
                .build()
                .inject(this);
        presenter.setView(this);
    }

    @OnClick(R.id.search)
    public void searchExhibition() {
        startActivity(new Intent(activity, SearchExhibitionActivity.class));
    }

    @OnClick(R.id.city)
    public void changeCity() {
        Intent intent = new Intent(activity, SelectCityActivity.class);
        intent.putExtra(ActivityConstant.LOCATED_CITY, city.getText().toString());
        startActivityForResult(intent, ActivityConstant.OPEN_SELECT_CITY_CODE);
    }

    @OnClick(R.id.month)
    public void changeMonth() {
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(activity, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                date.setText(monthList.get(options1));
                getExhibitionList(0, getSelectedCity(city.getText().toString()), getSelectedTime(monthList.get(options1)), false);
            }
        }).build();
        pvOptions.setPicker(monthList, null);
        pvOptions.show();
    }

    @Override
    public void setCurrentCity(final String location, boolean isLocated) {
        if (isLocated) {
            //是定位结果（初次进入页面）
            getExhibitionList(0, getSelectedCity(location), getSelectedTime(date.getText().toString()), false);
        } else {
            //不是定位结果，通过选择城市
            getExhibitionList(0, getSelectedCity(location), getSelectedTime(date.getText().toString()), false);
        }
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                city.setText(location);
            }
        });
    }

    @Override
    public void getExhibitionSuccess(List<ExhibitionModel> list) {
        if (refreshLayout.isLoading()) {
            adapter.add(list);
            refreshLayout.loadMoreFinish(list.isEmpty() ? State.LOAD_ALL : State.LOADING_SUCCEED);
        } else {
            adapter.refresh(list);
            refreshLayout.refreshFinish(State.REFRESH_SUCCEED);
        }
        //是否显示空提示
        refreshEmptyHintStatus(adapter.getItemCount() == 0);
    }

    @Override
    public void getExhibitionFailed() {
        refreshLayout.finishRefreshingOrLoadingStatus(false);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ActivityConstant.OPEN_SELECT_CITY_CODE:
                if (resultCode == Activity.RESULT_OK && data != null) {
                    setCurrentCity(data.getStringExtra(ActivityConstant.SELECT_CITY_COMPLETE), false);
                }
                break;
        }
    }

    /**
     * 初始化月份列表
     */
    private void initMonthList() {
        monthList = new ArrayList<>();
        monthList.add(getResources().getString(R.string.all_time));
        int currentYear = Calendar.getInstance().get(Calendar.YEAR);
        int currentMonth = Calendar.getInstance().get(Calendar.MONTH) + 1;
        for (int i = currentMonth; i < 15; i++) {
            if (currentMonth > 12) {
                monthList.add(String.valueOf(currentYear + 1) + "-" + String.format(Locale.getDefault(), "%02d", i % 13));
            } else {
                monthList.add(String.valueOf(currentYear) + "-" + String.format(Locale.getDefault(), "%02d", i % 13));
            }
        }
    }

    /**
     * 初始化地点和月份
     */
    private void initFilter() {
        date.setText(getResources().getString(R.string.all_time));
        //初始化地点
        getLocation();
    }

    /**
     * 获取地点
     */
    private void getLocation() {
        if (presenter != null) {
            presenter.getLocation();
        }
    }

    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        exhibitions.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));
        adapter = new ExhibitionListAdapter(null);
        exhibitions.setAdapter(adapter);
        exhibitions.setItemAnimator(new DefaultItemAnimator());
        new RefreshBuilder.Builder(refreshLayout)
                .setRefreshViewCreator(new DefaultRefreshViewCreator())
                .setLoadMoreViewCreator(new DefaultLoadMoreViewCreator())
                .setRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                        getExhibitionList(0, false);
                    }

                    @Override
                    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                        getExhibitionList(adapter.getItemCount(), false);
                    }
                }).build();
    }

    /**
     * 获取展会列表
     *
     * @param total    已获取展会总数
     * @param city     已选择的城市，全部城市则传null
     * @param month    年月，时间格式yyyy-MM
     * @param getLocal 是否是获取本地数据
     */
    private void getExhibitionList(int total, String city, String month, boolean getLocal) {
        getLocalData = getLocal;
        presenter.getExhibitionList(total, city, month, getLocal);
    }

    /**
     * 获取展会列表
     *
     * @param total    已获取展会总数
     * @param getLocal 是否是获取本地数据
     */
    private void getExhibitionList(int total, boolean getLocal) {
        getExhibitionList(total, getSelectedCity(city.getText().toString()), getSelectedTime(date.getText().toString()), getLocal);
    }

    /**
     * 获取选择的城市
     *
     * @return 城市名
     */
    private String getSelectedCity(String city) {
        if (city.equals(getResources().getString(R.string.locating)) ||
                city.equals(getResources().getString(R.string.locate_fail)) ||
                city.equals(getResources().getString(R.string.total_city))) {
            return null;
        }
        return city;
    }

    /**
     * 获取选择的日期
     *
     * @param time
     * @return
     */
    private String getSelectedTime(String time) {
        if (activity.getResources().getString(R.string.all_time).equals(time)) {
            return null;
        }
        return time;
    }

    /**
     * 是否显示空提示
     *
     * @param show
     */
    private void refreshEmptyHintStatus(boolean show) {
        if (getLocalData) {
            return;
        }
        noData.setVisibility(show ? View.VISIBLE : View.GONE);
    }


}
